//
//  JJLMPZViewController.m
//  Estate
//
//  Created by houzhen on 2017/11/10.
//  Copyright © 2017年 ttsx. All rights reserved.
//

#import "JJLMPZViewController.h"
#import "Tweet.h"
#import "JJRecordCell.h"
#import "JJMultitermRecordCell.h"
#import "JJTemperatuTreDetectionCell.h"
#import "JJLMTemperatureModel.h"



@interface JJLMPZViewController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate>{
    //title数组
    NSArray *titArr;
    
}
@property (nonatomic,strong) TPKeyboardAvoidingTableView *tableView; /**表格*/
@property(strong,nonatomic) UIImagePickerController *picker;
@property (strong, nonatomic) Tweet *curTweet;  /** 附件模型*/
@end

@implementation JJLMPZViewController

- (UIImagePickerController *)picker{
    if(!_picker){
        _picker = [[UIImagePickerController alloc] init];
        _picker.delegate = self;
        _picker.allowsEditing = NO;//设置可编辑
        _picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    }
    return _picker;
}
-(UITableView *)tableView{
    if(_tableView==nil){
        _tableView = [[TPKeyboardAvoidingTableView alloc] initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT) style:UITableViewStylePlain];
        _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator=NO;
        _tableView.delegate=self;
        _tableView.dataSource=self;
        [LSUtility setExtraCellLineHidde:self.tableView tabHeader:NO tabFooter:NO];
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        [_tableView registerNib:[UINib nibWithNibName:@"B_SwitchCell" bundle:nil] forCellReuseIdentifier:@"switch"];
        [_tableView registerNib:[UINib nibWithNibName:@"B_wuLiaoCell" bundle:nil] forCellReuseIdentifier:@"wuliao"];
        
        //新增记录数据cell
        [_tableView registerNib:[UINib nibWithNibName:@"JJRecordCell" bundle:nil] forCellReuseIdentifier:@"JJRecordCell"];
        //新增多项记录cell
        [_tableView registerNib:[UINib nibWithNibName:@"JJMultitermRecordCell" bundle:nil] forCellReuseIdentifier:@"JJMultitermRecordCell"];
        //新增现场温度检测cell
        [_tableView registerNib:[UINib nibWithNibName:@"JJTemperatuTreDetectionCell" bundle:nil] forCellReuseIdentifier:@"JJTemperatuTreDetectionCell"];
        [_tableView registerClass:[H1_ImagesCell class] forCellReuseIdentifier:kCellIdentifier_H1_ImagesCell];
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
    
    _curTweet = [[Tweet alloc] init];
    
    titArr=@[@"施工过程简述(按规范、图纸和施工组织设计作业情况):",@"工程质量、安全及环境问题或隐患(如有，必须附照片或摄影资料)",@"处理措施"];
    [self setData];
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(refresh:) name:@"RefreshImage_1" object:nil];
}
- (void)setData{
    WEAKSELF
    if(self.fahuanLM){
        self.selectedAssetURLs = [LSUtility quertFileImageType:@"RECORD_02_SIDE_04" andId:self.sideId andFilePathArr:self.fileArray];
        [self refresh:nil];
        
    }else{
        weakSelf.fahuanLM = [[JJLMFaHuanModel alloc]init];
        weakSelf.fahuanLM.isTechnicalMeasures = YES;
        weakSelf.fahuanLM.sketch = @"已按照图纸和施工组织设计施工，措施得当，施工过程符合规范要求";
        weakSelf.fahuanLM.quality = @"无质量问题和隐患";
        weakSelf.fahuanLM.measure = @"无";
        weakSelf.fahuanLM.measuredThickness = [NSMutableArray arrayWithObjects:@"",@"",@"",@"",@"",@"",nil];
        weakSelf.fahuanLM.temperatures = [NSMutableArray array];
        JJLMTemperatureModel *model = [[JJLMTemperatureModel alloc]init];
        [weakSelf.fahuanLM.temperatures addObject:model];
    }
    [self.tableView reloadData];
}
#pragma mark UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 5;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    WEAKSELF
    if(section == 1){
        return 4;
    }else if(section == 2){
        return weakSelf.fahuanLM.temperatures.count;
    }else if(section == 3){
        return titArr.count;
    }else{
        return 1;
    }
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *hView = [[UIView alloc]initWithFrame:CGRectMake(0,0,DEF_SCREEN_WIDTH, CELL_HEIGHT-10)];
    hView.backgroundColor=[UIColor colorWithRed:0.94 green:0.94 blue:0.94 alpha:1.00];
    if (section == 1){
        //增加区头 监理抽检数据记录
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, DEF_SCREEN_WIDTH, CELL_HEIGHT-10)];
        label.backgroundColor = [UIColor colorWithRed:0.94 green:0.94 blue:0.94 alpha:1.00];
        label.text = @"监理抽检数据记录：";
        label.font = [UIFont systemFontOfSize:16*BIZ];
        label.textColor = UIColorFromRGB(0x797979);
        [hView addSubview:label];
        return hView;
    }else{
        return hView;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0||section ==3) {
        return 10;
    }else if(section == 1){
        return 40;
    }else{
        return 0;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section==0){
        return 60*BIZ;
    }else if(indexPath.section==1){
        if(indexPath.row == 3){
            return 80*BIZ;
        }
        return 50*BIZ;
    }else if(indexPath.section == 2){
        return 140*BIZ;
    }else if(indexPath.section==3){
        return 130*BIZ;
    }else{
        return  [H1_ImagesCell cellHeightWithObj:_curTweet title:@"附件"];
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WEAKSELF
    //安全技术措施
    if (indexPath.section==0) {
        B_SwitchCell *cell=[tableView dequeueReusableCellWithIdentifier:@"switch" forIndexPath:indexPath ];
        cell.title.text = @"安全技术措施（或安全专项方案）落实\n情况（是否落实）";
        cell.sValueChangeBlock=^(UISwitch *sender){
            weakSelf.fahuanLM.isTechnicalMeasures = sender.on;
        };
        cell.isEdit=self.isEdit;
        //设置开关
        [cell.kaiguan setOn:self.fahuanLM.isTechnicalMeasures];
        return cell;
        //抽检数据记录
    }else if(indexPath.section == 1){
        //结构设计层厚度
        if(indexPath.row == 0){
            JJRecordCell *cell= [tableView dequeueReusableCellWithIdentifier:@"JJRecordCell"];
            cell.titleLabel.text = @"结构设计层厚度";
            cell.unitLabel.text = @"cm";
            cell.content.text = weakSelf.fahuanLM.designThickness;
            cell.contentType = DefaultMode;
            cell.contentChangeBlock =^(NSString *valueStr){
                weakSelf.fahuanLM.designThickness = valueStr;
            };
            cell.isEdit = self.isEdit;
            return cell;
        //松辅系数
        }else if (indexPath.row == 1){
            JJRecordCell *cell= [tableView dequeueReusableCellWithIdentifier:@"JJRecordCell"];
            cell.titleLabel.text = @"松辅系数";
            cell.content.text = weakSelf.fahuanLM.coefficient;
            cell.contentType = DefaultMode;
            cell.contentChangeBlock =^(NSString *valueStr){
                weakSelf.fahuanLM.coefficient = valueStr;
            };
            cell.isEdit = self.isEdit;
            
            return cell;
        //供料地点
        }else if (indexPath.row == 2){
            JJRecordCell *cell= [tableView dequeueReusableCellWithIdentifier:@"JJRecordCell"];
            cell.titleLabel.text = @"供热地点";
            cell.content.text = weakSelf.fahuanLM.heatingLocation;
            cell.contentType = ZifuMode;//键盘类型
            cell.contentChangeBlock =^(NSString *valueStr){
                weakSelf.fahuanLM.heatingLocation = valueStr;
            };
            cell.isEdit = self.isEdit;
            return cell;
        //实测松辅厚度(cm)
        }else{
            JJMultitermRecordCell *cell= [tableView dequeueReusableCellWithIdentifier:@"JJMultitermRecordCell"];
            cell.titleLabel.text = @"实测松辅厚度(cm)";
            cell.content_1.text = weakSelf.fahuanLM.measuredThickness[0];
            cell.content_2.text = weakSelf.fahuanLM.measuredThickness[1];
            cell.content_3.text = weakSelf.fahuanLM.measuredThickness[2];
            cell.content_4.text = weakSelf.fahuanLM.measuredThickness[3];
            cell.content_5.text = weakSelf.fahuanLM.measuredThickness[4];
            cell.content_6.text = weakSelf.fahuanLM.measuredThickness[5];
            cell.isEdit = self.isEdit;
            //6组数据
            cell.content_1ChangeBlock =^(NSString *valueStr){
                weakSelf.fahuanLM.measuredThickness[0] = valueStr;
            };
            cell.content_2ChangeBlock =^(NSString *valueStr){
                weakSelf.fahuanLM.measuredThickness[1] = valueStr;
            };
            cell.content_3ChangeBlock =^(NSString *valueStr){
                weakSelf.fahuanLM.measuredThickness[2] = valueStr;
            };
            cell.content_4ChangeBlock =^(NSString *valueStr){
                weakSelf.fahuanLM.measuredThickness[3] = valueStr;
            };
            cell.content_5ChangeBlock =^(NSString *valueStr){
                weakSelf.fahuanLM.measuredThickness[4] = valueStr;
            };
            cell.content_6ChangeBlock =^(NSString *valueStr){
                weakSelf.fahuanLM.measuredThickness[5] = valueStr;
            };
            
            return cell;
        }
        //此section 为现场温度检测数组 self.temperatureArray
    }else if (indexPath.section == 2){
        
            JJLMTemperatureModel *model = weakSelf.fahuanLM.temperatures[indexPath.row];
            JJTemperatuTreDetectionCell *cell= [tableView dequeueReusableCellWithIdentifier:@"JJTemperatuTreDetectionCell"];
                cell.titleLabel.text = @"现场温度检测";
            cell.isEdit = self.isEdit;

            if (indexPath.row == 0) {
                cell.addBtn.hidden = NO;
            }else{
                cell.addBtn.hidden = YES;
            }
        
            [cell.addBtn addTarget:self action:@selector(addTemperatuTre:) forControlEvents:UIControlEventTouchUpInside];

            //到场
            cell.dcField.text = model.attendance;
            cell.dcFieldChangeBlock  =^(NSString *valueStr){
                model.attendance = valueStr;
            };
            //初压
            cell.cyField.text = model.initial;
            cell.cyFieldChangeBlock  =^(NSString *valueStr){
                model.initial = valueStr;
            };
            //摊铺
            cell.tpField.text = model.pave;
            cell.tpFieldChangeBlock  =^(NSString *valueStr){
                model.pave = valueStr;
            };
            //终压
            cell.zyField.text = model.finals;
            cell.zyFieldChangeBlock  =^(NSString *valueStr){
                model.finals = valueStr;
            };
        
            return cell;
        
    } else if(indexPath.section == 3){
        B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"wuliao" forIndexPath:indexPath];
        cell.title.text = titArr[indexPath.row];
        //施工过程简述
        if (indexPath.row ==0){
            cell.text.text = self.fahuanLM.sketch;
            //工程质量、安全
        }else if (indexPath.row == 1){
            cell.text.text = self.fahuanLM.quality;
            //处理措施
        }else if (indexPath.row == 2){
            cell.text.text = self.fahuanLM.measure;
        }
        cell.textValueChangedBlock=^(NSString *valueStr){
            //施工过程简述
            if (indexPath.row ==0){
                weakSelf.fahuanLM.sketch = valueStr;
                //工程质量、安全
            }else if (indexPath.row == 1){
                weakSelf.fahuanLM.quality = valueStr;
                //处理措施
            }else if (indexPath.row == 2){
                weakSelf.fahuanLM.measure = valueStr;
            }
        };
        cell.isEdit=weakSelf.isEdit;
        return  cell;
    }else{
        H1_ImagesCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_H1_ImagesCell forIndexPath:indexPath];
        cell.isEdit=self.isEdit;
        [cell setTitle:@"附件"];
        cell.curTweet = _curTweet;
        cell.addPicturesBlock = ^(){
            [weakSelf showActionForPhoto];
        };
        __block H1_ImagesCell *cellblock = cell;
        cell.deleteTweetImageBlockUrl = ^(TweetImage *toDelete,NSString *deurl){
            [cellblock.curTweet.tweetImages removeObject:toDelete];
            [weakSelf.selectedAssetURLs removeObject:deurl];
            [weakSelf refresh:nil];
        };
        return cell;
    }
}

#pragma mark 设置可以进行编辑
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%zd -- %zd",indexPath.section,indexPath.row);
    if (indexPath.section == 2 && indexPath.row > 0) {
        return YES;
    }else{
        return NO;
    }
}
#pragma mark 设置编辑的样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

#pragma mark 设置处理编辑情况
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    WEAKSELF
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [weakSelf.fahuanLM.temperatures removeObjectAtIndex:indexPath.row-1];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

-(void)addTemperatuTre:(UIButton *)button{
    WEAKSELF
    JJLMTemperatureModel *model = [[JJLMTemperatureModel alloc]init];
    [weakSelf.fahuanLM.temperatures addObject:model];
    [self.tableView reloadData];
}

- (void)refresh:(id)sender{
    if(self.selectedAssetURLs!=nil){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            self.curTweet.selectedAssetURLs =self.selectedAssetURLs;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:4]] withRowAnimation:UITableViewRowAnimationFade];
            });
        });
    }
}



#pragma mark UIActionSheet M
- (void)showActionForPhoto{
    //    @weakify(self);
    [[UIActionSheet bk_actionSheetCustomWithTitle:nil buttonTitles:@[@"拍照", @"从相册选择"] destructiveTitle:nil cancelTitle:@"取消" andDidDismissBlock:^(UIActionSheet *sheet, NSInteger index) {
        
        [self photoActionSheet:sheet DismissWithButtonIndex:index];
        
    }] showInView:self.view];
}

- (void)photoActionSheet:(UIActionSheet *)sheet DismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        //拍照
        if (_curTweet.tweetImages.count >= 9) {//照片最多这么多
            kTipAlert(@"最多只可选择9张照片，已经选满了。先去掉一张照片再拍照呗～");
            return;
        }
        [self presentViewController:self.picker animated:YES completion:nil];//进入照相界面
    }else if (buttonIndex == 1){
        PictureViewController *picCtr=[[PictureViewController alloc]init];
        picCtr.flag=@"file";
        NSMutableArray *array = [self.selectedAssetURLs valueForKeyPath:@"@distinctUnionOfObjects.self"];
        picCtr.selectedImages=[[NSMutableArray alloc] initWithArray:array];
        picCtr.selectedImageBlock=^(NSMutableArray *array){
            for (NSString *path in array) {
                //添加图片路径到已选数组
                [self.selectedAssetURLs addObject:path];
            }
        };
        [self.navigationController pushViewController:picCtr animated:YES];
    }
}

#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
    self.curTweet.editImageView = [[EditImageView alloc]initWithImage:image];
    WEAKSELF
    self.curTweet.editImageView.completeBlock = ^(NSString *path) {
        //添加选择附件
        [weakSelf.curTweet addASelectedAssetURL:path];
        [weakSelf.selectedAssetURLs addObject:path];
        //刷新指定行
        [weakSelf.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:4]] withRowAnimation:UITableViewRowAnimationFade];
    };
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
